import router from "../router/index.js"
import {ElMessage} from "element-plus";
import http from "@/utils/http.js";

const tools = {

    // isLogin() {
    //     return localStorage.getItem("currentUser") !== null;
    // },
    // getCurrentUser() {
    //     return JSON.parse(localStorage.getItem("currentUser"));
    // },
    getToken() {
        return localStorage.getItem("token");
    },
    removeToken() {
        localStorage.removeItem("token");
    },
    // 解析JWT token
    parseToken() {
        const token = this.getToken();
        if (!token) return null;
        try {
            // JWT token的格式是 header.payload.signature
            const base64Url = token.split('.')[1];
            const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
            const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
                return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
            }).join(''));
            const payload = JSON.parse(jsonPayload);
            
            // 验证必要的字段是否存在
            if (!payload.id || !payload.name || !payload.type) {
                console.error('Token缺少必要字段');
                this.removeToken();
                return null;
            }
            
            return payload;
        } catch (error) {
            console.error('Token解析失败:', error);
            this.removeToken();
            return null;
        }
    },
    // 获取用户类型
    getUserType() {
        const payload = this.parseToken();
        return payload ? payload.type : null;
    },
    // 获取用户ID
    getUserId() {
        const payload = this.parseToken();
        return payload ? payload.id : null;
    },
    // 获取用户名
    getUserName() {
        const payload = this.parseToken();
        return payload ? payload.name : null;
    },
    formatDateToYYYYMMDD(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-based
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    }
}
export default tools
